#include "user_threads.h"
#include "user_mutex.h"

#include <stdio.h>
#include <assert.h>

#define LOOPS 10
#define FIB 30

uthread_mutex_t mutex;

static int fibonaci(unsigned int n)
{
	if (n < 2) {
		return n;
	}
	return fibonaci(n-2) + fibonaci(n-1);
}

int thread0(void * arg)
{
    int i;
    for (i = 0; i < LOOPS; ++i) {
        printf("uthread #%d\n", uthread_self());
	fibonaci(FIB);
    }
	uthread_mutex_lock(mutex);
	printf("mutex locked by thread 0\n");
	uthread_mutex_unlock(mutex);
    return 0;
}

int thread1(void * arg)
{
    int i;
	uthread_mutex_lock(mutex);
	printf("mutex locked ny thread 1\n");
    for (i = 0; i < LOOPS*2; ++i) {
        printf("uthread #%d\n", uthread_self());
		fibonaci(FIB);
    }
	uthread_mutex_unlock(mutex);
    return 0;
}

int main(int argc, char ** argv)
{
    uthread_init();
	int res = uthread_mutex_init(&mutex);
	assert(res==MUTEX_SUCCESS);
    uthread_create(&thread1, NULL, UTHREAD_MIN_PRIO);
    thread0(NULL);
    uthread_mutex_destroy(mutex);
    return 0;
}
